<template>
  <div class="svg-list-container">
    <el-card class="list-card" shadow="hover">
      
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索组态图名称或主题..."
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
          style="max-width: 400px;"
        />
      </div>
      
      <el-table :data="filteredDataList" style="width: 100%" :stripe="true" :border="true" highlight-current-row>
        <el-table-column type="index" label="序号" width="80" align="center" />
        
        <el-table-column prop="t_name" label="组态名称" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-tooltip
              content="点击复制预览地址"
              placement="top"
            >
              <el-tag 
                type="primary" 
                style="cursor: pointer; user-select: none;"
                @click="copyPreviewUrl(scope.row.t_id)"
              >
                {{ scope.row.t_name }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column prop="t_topic" label="页面主题" min-width="150" show-overflow-tooltip />
        
        <el-table-column prop="t_width" label="页面宽度" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.t_width }}px</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="t_height" label="页面高度" width="120" align="center">
          <template #default="scope">
            <span>{{ scope.row.t_height }}px</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="t_background_color" label="背景颜色" width="140" align="center">
          <template #default="scope">
            <el-tag :color="scope.row.t_background_color" style="color: #fff">
              {{ scope.row.t_background_color }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="320" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" :icon="View" @click="preview(scope.row.t_id)" style="margin-right: 4px;">
              预览
            </el-button>
            <el-button type="warning" size="small" :icon="Edit" @click="edit(scope.row.t_id)" style="margin-right: 4px;">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="del(scope.row.t_id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getList, getTopoById, delTopo } from "@/api/business";
import {
  ElMessageBox,
  ElMessage,
  ElTable,
  type TableColumnCtx,
} from "element-plus";
import { Close, View, Edit, Delete, Search } from "@element-plus/icons-vue";
import axios from "axios";
const router = useRouter();
//调用后端成功后的回调父组件
const emit = defineEmits(["closePageBack", "closeDialog"]);

const dataList = ref([]);
const searchKeyword = ref("");
const filteredDataList = ref([]);
// const backendUrl = getCurrentInstance()?.appContext.config.globalProperties.$backendUrl
interface User {
  t_id: string;
  t_name: string;
  t_topic: string;
  t_width: string;
  t_height: string;
  t_background_color: string;
}
const tableRef = ref<InstanceType<typeof ElTable>>();

const resetDateFilter = () => {
  tableRef.value!.clearFilter(["t_name"]);
};

const formatter = (row: User, column: TableColumnCtx<User>) => {
  return row.t_name;
};

const filterHandler = (
  value: string,
  row: User,
  column: TableColumnCtx<User>
) => {
  const property = column["property"];
  return row[property] === value;
};
const getTopoList = () => {
  const params = {
    curPage: 1,
    pageSize: 1000, // 获取所有数据
    ...(searchKeyword.value.trim() ? { name: searchKeyword.value } : {})
  };
  
  getList(params).then((res) => {
    if (res.code == 200) {
      dataList.value = res.data;
      filteredDataList.value = res.data;
    }
  });
};
getTopoList();

// 搜索功能
const handleSearch = () => {
  // 调用后端接口搜索
  getTopoList();
};
// 生成预览URL
const getPreviewUrl = (tId: string) => {
  const to = router.resolve({
    name: "prview",
    params: { id: tId },
  });
  return window.location.origin + to.href + "?tId=" + tId;
};

//打开预览
const preview = (tId: string) => {
  const url = getPreviewUrl(tId);
  window.open(url, "_blank");
};

// 复制预览URL
const copyPreviewUrl = (tId: string) => {
  const url = getPreviewUrl(tId);
  
  // 使用 Clipboard API 复制
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(url).then(() => {
      ElMessage.success("预览地址已复制到剪贴板");
    }).catch(() => {
      fallbackCopy(url);
    });
  } else {
    fallbackCopy(url);
  }
};

// 降级方案：使用传统的复制方法
const fallbackCopy = (text: string) => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';
  textArea.style.left = '-999999px';
  textArea.style.top = '-999999px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  
  try {
    const successful = document.execCommand('copy');
    if (successful) {
      ElMessage.success("预览地址已复制到剪贴板");
    } else {
      ElMessage.error("复制失败，请手动复制");
    }
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  } finally {
    document.body.removeChild(textArea);
  }
};

//编辑该组态图
const edit = (tId: string) => {
  getTopoById(tId).then((res) => {
    if (res.code == 200 && res.data != "") {
      emit("closePageBack", res.data[0]);
      // 关闭弹窗
      emit("closeDialog");
    } else {
      ElMessage({
        message: "调用后端失败",
        type: "error",
      });
    }
  }).catch(() => {
    ElMessage({
      message: "调用后端失败",
      type: "error",
    });
  });
};

//删除组态图
const del = (tId: string) => {
  ElMessageBox.confirm("确认删除当前组态图吗？").then(() => {
    delTopo(tId).then((res) => {
      if (res.code == 200) {
        //调用后端成功后的回调父组件
        ElMessage({
          message: "删除成功！",
          type: "success",
        });
        getTopoList();
      }
    });
  });
};
</script>

<style lang="scss" scoped>
.svg-list-container {
  width: 100%;
  max-height: 65vh;
  overflow: hidden;
  
  .list-card {
    height: 100%;
    border-radius: 8px;
    
    :deep(.el-card__header) {
      display: none;
    }
    
    :deep(.el-card__body) {
      padding: 0;
      max-height: 55vh;
      overflow-y: auto;
      overflow-x: auto;
      
      &::-webkit-scrollbar {
        width: 6px;
        height: 6px;
      }
      
      &::-webkit-scrollbar-track {
        background: rgba(0, 0, 0, 0.05);
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.2);
        border-radius: 3px;
        
        &:hover {
          background: rgba(0, 0, 0, 0.3);
        }
      }
    }
    
    :deep(.el-card__header) {
      padding: 16px 20px;
      border-bottom: 1px solid #e4e7ed;
    }
  }
}

.search-section {
  padding: 20px 20px 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: flex-start;
  background: #fafafa;
}

:deep(.el-table) {
  .el-table__body-wrapper {
    max-height: 45vh;
    overflow-y: auto !important;
  }
  
  .el-table__header {
    th {
      background: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }
  
  .el-table__row {
    &:hover {
      background: #f5f7fa;
    }
  }
  
  // 防止表格溢出
  .el-table__body,
  .el-table__header {
    width: 100% !important;
    table-layout: auto !important;
  }
  
  th,
  td {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

:deep(.el-table__body) {
  .el-button {
    margin-right: 4px;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

:deep(.el-tag) {
  margin: 0;
}
</style>
